<template>
    <div class="fabuPage">
        <div class="fabuTitle">
            <p>发布视频</p>
            <img src="@as/img/xuanchuan_video_icon.png" alt="">

        </div>
        <div id="loadingToast" v-if="loading">
            <div class="weui-mask_transparent"></div>
            <div class="weui-toast">
                <i class="weui-loading weui-icon_toast"></i>
                <p class="weui-toast__content">附件上传中，请耐心等候...</p>
            </div>
        </div>
        <div class="fabuForm">
                <div class="fabuFormItem">
                    <p class="p-title">视频标题</p>
                    <input type="text" placeholder="请输入视频标题" class="input-title" v-model="title">
                </div>
                <div class="fabuFormItem">
                    <p class="p-title">选择分类</p>
                    <p class="selectCountp">{{className}}<span class="iconshuju_icon_xiala iconfont"></span>
                        <mu-select  v-model="normal.value" @change="changeClassify">
                            <mu-option v-for="(item,index) in orgArray" :key="index" :label="item.class_name" :value="item.id"></mu-option>
                        </mu-select>
                    </p>
                </div>
            <div class="fabuFormItem" style="margin-bottom: 20px">
                <p class="p-title">上传视频 <span>*视频大小不超过100M</span></p>
                <div class="fabuFormFile" >
                    <p><span class="iconfont  iconxuanchuan_icon_tianjia"></span>上传视频文件
                        <input type="file" ref="fileInput" accept="video/*"  placeholder="请输入视频标题" @change="addVideo">
                    </p>
                </div>
            </div>
            <div class="previewVideo" v-if="hasVideo">
                <img v-show="iconPlayShow" class="icon_play" @click="playvideo" src="http://douliu.jishiyoo.com/images/icon_play.png"/>
                <video id="video" :src=videoStr :poster=photoStr></video>
            </div>
            <div class="fabuFormItem" >
                <p class="p-title">上传视频封面图 </p>
                <div class="fabuFormFile">
                    <p><span class="iconfont  iconxuanchuan_icon_tianjia"></span>上传封面
                        <input type="file" ref="fileInput1" accept="image/*"   @change="addImg">
                    </p>
                </div>
            </div>
            <!--<div class="hasImg" v-if="hasImg">-->
                <!--<img :src=photoStr alt="">-->
            <!--</div>-->

                <div class="fabuBtn">
                    <span @click.stop="fabu" v-if="complete" class="complete">发布</span>
                    <span  v-if="!complete" class="no-complete">发布</span>
                </div>
        </div>
    </div>
</template>
<script>
    import * as qiniu from 'qiniu-js';
    import Toast  from 'muse-ui-toast';
    import {mapMutations} from 'vuex'
    export default({
        data(){
            return{
                normal:{},
                orgArray:[],
                iconPlayShow:true,
                className:'请选择视频分类',
                classId:'',
                hasVideo:false,
                token:'',
                loading:false,
                videoStr:'',
                title:'',
                photoStr:'https://media.71ydj.com/FqERNKcrA8oic4OMiHW3C6GWqYjr#',
                hasImg:false,
                duration:'',
                complete:false
            }
        },
        methods:{
            ...mapMutations(['changeSubNav']),
            uploadFile(e){
              console.log(e)
            },
            getToken(){
                this.$http.post('/index/index/qiniu',{
                }).then((res)=>{
                    if(res.code=='200'){
                        this.token =res.data.token;
                    }
                })
            },
            addImg(){
                let that =this;
                var files =this.$refs.fileInput1.files
                var url = window.URL || window.webkitURL || window.mozURL ;
                if(files[0]){
                    var observable = qiniu.upload(files[0], null, this.token,null)
                    var observer = {
                        next(res){
                            console.log(res.total.percent)
                        },
                        error(err){
                            console.log(err)
                        },
                        complete(res){
                            that.loading =false;
                            that.hasImg =true;
                            var str ='https://media.71ydj.com/'+ res.hash+'#';
                            that.photoStr =str;
                        }
                    }
                    var subscription = observable.subscribe(observer) // 上传开始
                }
            },
            addVideo(){
                let that =this;
                that.loading =true;
                var files =this.$refs.fileInput.files;
                var url = window.URL || window.webkitURL || window.mozURL ;
                if(files[0]){
                    that.loading =true
                    if(files[0].size/1024>51200){
                        alert('视频大小不超过50M')
                        return  false
                    }
                    var observable = qiniu.upload(files[0], null, this.token,null)
                    var observer = {
                        next(res){
                            console.log(res.total.percent)
                        },
                        error(err){
                            console.log(err)
                        },
                        complete(res){
                            that.loading =false;
                            that.hasVideo =true;
                            var str ='https://media.71ydj.com/'+ res.hash;
                            that.videoStr =str;
                            that.loading =false;
                            that.getDurtion();
                            that.complete =true;
                            that.$nextTick((function () {
                             that.getDurtion();
//                                this.$http.get(that.videoStr+'?avinfo').then((res)=>{
//                                    console.log(res.format.duration)
//                                    that.complete =true;
//                                })
////                                setTimeout(()=>{
////                                    that.duration =document.getElementById('video').duration;
////                                    alert(that.duration)
////                                    if(that.duration){
////                                        that.complete =true;
////                                    }
////                                    console.log(document.getElementById('video').duration)
////                                },2000)
                            }))
                        }
                    }
                    var subscription = observable.subscribe(observer) // 上传开始
                }
            },
            //this.asiox
            getDurtion(){
                this.axios.get(this.videoStr+'?avinfo',{}).then(
                    (res) =>{
                        this.duration =parseInt(res.format.duration);
                    }
                )
            },
            playvideo(event) {
                let video = document.querySelectorAll('video')[0];
                this.iconPlayShow = false;
                this.playOrPause = true;
                video.style.display = "";
                video.play();
                if (this.isiOS) {
                    if(video.canplaythrough){
                        this.isVideoShow = false;
                    }
                    //获取宽比
                    let docB = parseFloat(video.videoWidth/documentW);
                    // 计算视频最适高度
                    let realH = parseInt(video.videoHeight/docB);
                    $('.video_container').height(realH);
                    // $('.video_cont').height(realH);
                    video.addEventListener('canplaythrough',()=>{
                        //获取宽比
                        docB = parseFloat(video.videoWidth/documentW);
                        // 计算视频最适高度
                        realH = parseInt(video.videoHeight/docB);

                        $('.video_container').height(realH);
                        //将本视频已缓存 存个标识
                        this.currentVideo.canplaythrough=true;
                        this.isVideoShow = false;
                    });

                }else{
                    this.isVideoShow = false;
                }
                window.onresize = function () {
                    video.style.width = window.innerWidth + "px";
                    video.style.height = window.innerHeight + "px";
                };
                if (!this.isiOS) {
//                    this.checkAnPlay(video)
                }
            },
            changeClassify(e){
                this.orgArray.forEach((ele,index)=>{
                    if(ele.id==e){
                        this.className =ele.class_name;
                    }
                })
                this.classId =e;
                this.normal.value =e;
            },
            getClassList(){
                this.$http.post('/app/NewCustom/video_class',{
                    org_id:JSON.parse(Cookies.get('user_71ydj')).organization_id,
                    page:100,
                }).then((res)=>{
                    if(res.code=='200'){
                        this.orgArray =res.data;
                    }
                })
            },
            fabu(){
                console.log(this.photoStr);
                if(!this.duration){
                    this.duration=this.getDurtion();
                }
                if(this.title==''||this.photoStr==''||this.videoStr==''||this.classId==''){
                    Toast.error('请检查相关数据是否完善');
                    return false
                }else{
                    this.$http.post('/app/NewCustom/add_video',{
                        title:this.title,
                        class_id:this.classId,
                        video_address:this.videoStr,
                        uid:JSON.parse(Cookies.get('user_71ydj')).id,
                        org_id:JSON.parse(Cookies.get('user_71ydj')).organization_id,
                        low_source:this.photoStr,
                        video_duration:this.duration
                    }).then((res)=>{
                        if(res.code==200){
                            Toast.success('视频发布成功,请等待后台审核')
                            let Navsenior =JSON.parse(localStorage.getItem('Navsenior'));
                            console.log(Navsenior)
                            Navsenior.forEach((e,index)=>{
                                if(e.class_name=='党建微视'){
                                    console.log(index)
                                    this.changeSubNav({
                                        class_id: Navsenior[index].id,
                                        status:Navsenior[index].status,
                                        selectedId:index
                                    })
                                }
                            })
                            this.$store.commit('changeIndex',{
                                selectName:'党建微视'
                            });
                            this.$router.replace({
                                path:'/propaganda/video'
                            });
                            // this.$router.push('/propaganda/video')
                        }else{
                            Toast.error(res.msg)
                        }

                    }).catch((err)=>{
                        Toast.error(err)
                    })
                }
            },
            //设置微信分享
            getWxShare() {
                let that = this;
                let obj = {
                    video_id: this.video_id,
                    store_id: this.store_id,
                    openid: this.tOpenid,
                    url: encodeURI(window.location.href)
                }
                Ajax("get", '/api/item/wx/share', obj).then(res => {
                    let data = res.data;
                    that.wx_share = data;
                    setTimeout(() => {
                        that.wxShare();
                    }, 500)
                }).catch(err => {
                });
            },
            wxShare() {
                let that = this;
                wx.config({
                    debug: false,
                    appId: that.wx_share.appId, // 和获取Ticke的必须一样------必填，公众号的唯一标识
                    timestamp: that.wx_share.timestamp, // 必填，生成签名的时间戳
                    nonceStr: that.wx_share.nonceStr, // 必填，生成签名的随机串
                    signature: that.wx_share.signature, // 必填，签名，见附录1
                    //需要分享的列表项:发送给朋友，分享到朋友圈
                    jsApiList: ["updateTimelineShareData", "updateAppMessageShareData", "onMenuShareTimeline", "onMenuShareAppMessage"]
                });
                //处理验证失败的信息
                wx.error(function (res) {
//                       alert(JSON.stringify(res));
                });
                let userData = JSON.parse(get_cache('userData'));
                let channel_id = get_cache('channel_id');
                if (!channel_id || channel_id == 'null') {
                    channel_id = ''
                }
                let share_title = that.currentVideo.author + '：' + that.currentVideo.title;
                let share_des = '每天进步30秒';
                let share_img = that.currentVideo.cover + '?x-oss-process=image/resize,w_200/watermark,image_dnBsYXkucG5nP3gtb3NzLXByb2Nlc3M9aW1hZ2UvcmVzaXplLFBfNjA,t_90,g_se,x_40,y_120';

                if (this.currentVideo.video_id == 0) {
                    //广告分享
                    share_title = this.currentVideo.title;
                    share_img = this.currentVideo.cover;
                    history.replaceState({}, '每天进步30秒', `/m/card/sale?source=card&openid=${userData.openid}&channel_id=${channel_id}`);
                } else {
                    history.replaceState({}, '每天进步30秒', `/m/video/detail?video_id=${this.currentVideo.video_id}&channel_id=${channel_id}&store_id=${this.store_id}&openid=${userData.openid}&tag_id=${this.tag_id}&source=videoDetail&end`);
                }
                let share_url = window.location.href;

                wx.ready(() => {
                    WeixinJSBridge.call('showOptionMenu');
                    if (this.isiOS) {
                        //分享到朋友圈
                        wx.updateTimelineShareData({
                            title: share_title, // 分享标题
                            desc: share_des, // 分享描述
                            link: share_url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                            imgUrl: share_img, // 分享图标
                            success: function (res) {
                                // 用户确认分享后执行的回调函数
//                            showTips("成功分享朋友圈")
                            },
                            cancel: function (res) {
                                // 用户取消分享后执行的回调函数
                                // showTips("取消分享到朋友圈返回:" + res);
                            }
                        });
                        //分享给朋友
                        wx.updateAppMessageShareData({
                            title: share_title, // 分享标题
                            desc: share_des, // 分享描述
                            link: share_url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                            imgUrl: share_img, // 分享图标
                            type: "", // 分享类型,music、video或link，不填默认为link
                            dataUrl: "", // 如果type是music或video，则要提供数据链接，默认为空
                            success: function (res) {
                                // 用户确认分享后执行的回调函数
//                            showTips("成功分享给朋友")
                            },
                            cancel: function (res) {
                                // 用户取消分享后执行的回调函数
                            }
                        });
                    } else {
                        //分享到朋友圈
                        wx.onMenuShareTimeline({
                            title: share_title, // 分享标题
                            desc: share_des, // 分享描述
                            link: share_url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                            imgUrl: share_img, // 分享图标
                            success: function (res) {
                                // 用户确认分享后执行的回调函数
                                that.actionRecord('relay')
                            },
                            cancel: function (res) {
                                // 用户取消分享后执行的回调函数
                                // showTips("取消分享到朋友圈返回:" + res);
                            }
                        });
                        //分享给朋友
                        wx.onMenuShareAppMessage({
                            title: share_title, // 分享标题
                            desc: share_des, // 分享描述
                            link: share_url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                            imgUrl: share_img, // 分享图标
                            type: "", // 分享类型,music、video或link，不填默认为link
                            dataUrl: "", // 如果type是music或video，则要提供数据链接，默认为空
                            success: function (res) {
                                // 用户确认分享后执行的回调函数
                                that.actionRecord('relay')
                            },
                            cancel: function (res) {
                                // 用户取消分享后执行的回调函数
                            }
                        });
                    }
                })

            }
        },
        mounted(){
            if(!Cookies.get('user_71ydj')){
                this.$router.push({
                    path:'/mine'
                })
                return false
            }
            this.$progress.done();
            this.getClassList();
            this.getToken()
        }
    })
</script>
<style lang="scss" scoped="">
.fabuPage{
    background: white;
    .fabuTitle{
        font-size: 28px;
        color: rgba(51, 51, 51, 1);
        font-weight: bold;
        height: 139px;
        margin-left: 16px;
        p{
            padding-top: 36px;
            display: inline-block;

        }
        img{
            width: 130px;
            height: 140px;
            float: right;
        }
    }
    .hasImg{
        padding: 0 16px;
        width: 100%;
        height: 160px;
        margin-top: -20px;
        margin-bottom: 20px;
        img{
            width: 100%;
            height: 100%;
        }
    }
    .fabuFormItem{
        padding: 0 16px;
        line-height: 1;
        margin-bottom: 28px;
        .p-title{
            font-size: 16px;
            color: rgba(51, 51, 51, 1);
            margin-bottom: 14px;
            line-height: 1;
            span{
                color: rgba(204, 204, 204, 1);
                font-size: 10px;
                margin-left: 10px;
            }
        }
        .input-title,.selectCountp,.fabuFormFile{
            margin: 0;
            padding: 0;
            display: inline-block;
            border: none;
            outline: none;
            width: 100%;
            font-size: 14px;
            height: 40px;
            border: 1px solid rgba(221, 221, 221, 1);
            line-height: 40px;
            padding-left: 21px;
            box-sizing: border-box;
            -webkit-box-sizing: border-box;
            color: rgba(204, 204, 204, 1);
        }
        .fabuFormFile{
            p{
                position: relative;
                height: 100%;
                background: rgba(248, 248, 248, 1);
                font-size: 12px;
                color:rgba(153, 153, 153, 1) ;
                text-align: center;
                margin-left: -21px;
                margin-top: 0;
                .iconfont{
                    font-size: 10px;
                }
                input{
                    position: absolute;
                    left: 0;
                    top:0;
                    width: 100%;
                    height: 100%;
                    opacity: 0;
                }
            }

        }
        .selectCountp{
           position: relative;
            .iconfont{
                position: absolute;
                right: 12px;
                top:0%;
                color: rgba(204, 204, 204, 1);
            }
            .mu-input{
                position: absolute;
                left: 0;
                top:0px;
                width: 100%;
                height: 100%;
                opacity: 0;
            }
        }

    }
    .previewVideo{
        padding: 0 16px;
        width: 100%;
        height: 193px;
        margin-top: 15px;
        overflow: hidden;
        position: relative;
        margin-bottom: 20px;
        video{
            width: 100%;
            height:193px;
            /*object-fit:cover*/
        }
    }
    .fabuBtn{
        padding: 0 16px;
        text-align: center;
        height: 44px;
        line-height: 44px;
        font-size: 16px;
        color: white;
        margin-top:60px;
        border-radius: 6px;
        .complete{
            display: inline-block;
            width: 100%;
            height: 100%;
            background: rgba(235, 77, 68, 1);
        }
        .no-complete{
            display: inline-block;
            width: 100%;
            height: 100%;
            background:#f8f8f8;
        }
    }
}
.icon_play {
    position: absolute;
    top: 50%;
    right: 0;
    left: 0;
    bottom: auto;
    margin: auto;
    z-index: 999;
    width: 64px;
    height: 64px;
    margin-top: -32px;
    color: rgba(255,255,255,0.4);
    /*border-radius: 50%;*/
}


.weui-mask_transparent {
    position: fixed;
    z-index: 1000;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
}
.weui-toast {
    position: fixed;
    z-index: 5000;
    width: 130px;
    max-height: 100px;
    top: 180px;
    left: 50%;
    margin-left: -65px;
    background: rgba(17, 17, 17, 0.7);
    text-align: center;
    border-radius: 5px;
    color: #FFFFFF;
}
.weui-icon_toast.weui-loading {
    margin: 32px 0 0;
    width: 38px;
    height: 38px;
    vertical-align: baseline;
}
.weui-loading {
    width: 20px;
    height: 20px;
    display: inline-block;
    vertical-align: middle;
    -webkit-animation: weuiLoading 1s steps(12, end) infinite;
    animation: weuiLoading 1s steps(12, end) infinite;
    background: url("Loading.png");
    background-size: 100%;
}
.weui-toast__content {
    margin: 0 0 16px;
    font-size: 14px;
}
</style>